//
// Created by wangjunjun on 2024/3/13.
//

#include "generic.h"
#include "../log/log.h"
#include <chrono>

#include <iostream>

#define MKDIR_CMD "mkdir -p "
CGeneric::CGeneric():m_TimeStr(""){

}
CGeneric::~CGeneric(){

}
//获取时间戳函数
std::string CGeneric::getCurrentTime() {
    time_t now = time(nullptr);
    char formattedTime[15];
    strftime( formattedTime, sizeof(formattedTime), "%Y%m%d%H%M%S", localtime(&now));
    return std::string(formattedTime);
}
std::string CGeneric::GetTimeStamp(){
    auto current_time = std::chrono::system_clock::now();
    auto current_timestamp = std::chrono::time_point_cast<std::chrono::milliseconds>(current_time).time_since_epoch().count();
    return std::to_string(current_timestamp);
}
void CGeneric::createDirectory(std::string dogSn, std::string dataType){
    // 写入独占锁
    std::unique_lock<std::mutex>  lock(m_Mtx);
    std::string directoryName ="./" + dogSn + "/"  + dataType+"/" + getCurrentTime();
    LOG_INFO(" CGeneric::createDirectory {} ",  directoryName);
    std::string cmd = MKDIR_CMD + directoryName;
    // 清除map　
    m_DataMap.erase(dataType);
    //插入h数据
    m_DataMap.insert(std::make_pair(dataType,  directoryName));
    //如果创建成功插入map
    int result = system(cmd.c_str());
    if(result == 0){
        lock.unlock();
        LOG_INFO("Directory  created successfully !");
    }else{
        lock.unlock();
        LOG_ERROR("Directory  created Failed !");
    }
    return;
}


//返回时间戳函数
std::string CGeneric::GetPathFile(const std::string &dataType){
    std::unique_lock<std::mutex > lock(m_Mtx); //读取共享
    auto it = m_DataMap.find(dataType);
    if(it != m_DataMap.end()){
      //  std::cout << it->second << std::endl;
        lock.unlock();
        return  it->second;
    }else{
    //    LOG_ERROR("Not Find The Key {}", it->first);
        lock.unlock();
        return "";
    }

}
//判断目录是否存在
bool CGeneric::dirIsExists(const std::string &path){
    struct stat info;
    if(stat(path.c_str(), &info) != 0){
        LOG_ERROR("{} Is not Exists!", path.c_str());
        return false;
    }
    return (info.st_mode & S_IFDIR)!=0;
}